import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS} from '../constants';
import TextInput from 'Shared/components/TextInput';
import SelectAlert from '../common/SelectAlert';
import {language, injectIntl} from './intl';
import {conventEnumValueToString, conventSorter} from '../utils';
import styles from './style.css';
import {saleOrderQuery} from './api';
import {saleOrderPriceTerms, saleOrderType, saleOrderTransportType, currency, paymentType} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
const FormItem = Form.Item;
import moment from 'moment';

class SaleOrderPanel extends PureComponent {
    state = {
        code: '',
        orderType: undefined,
        carrierCode: '',
        batchNumber: '',
        createTime: [],
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        selectedRowKeys: [],
        selectedRows: [],
    }
    
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: pagination.current - 1
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }

    toggleShowTags=() => {
        this.setState({
            showTags: !this.state.showTags
        });
    }
    onQuery = condition => {
        this.setState({isFetching: true});
        saleOrderQuery(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            orderType: this.state.orderType,
            carrierCode: this.state.carrierCode,
            batchNumber: this.state.batchNumber,
            createTime: this.state.createTime,
            brandId: this.props.brandId,
            dealerId: this.props.dealerId,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        const conventDate = condition => {
            const {createTime, ...others} = condition;
            if(!createTime || createTime.length === 0) return condition;
            return {
                ...others,
                beginCreateTime: moment(createTime[0]).toISOString(),
                endCreateTime: moment(createTime[1]).toISOString(),
            };
        };
        this.onQuery(conventDate(condition));
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }

    onClickReset = () => {
        this.setState({
            code: '',
            orderType: undefined,
            carrierCode: '',
            batchNumber: '',
            createTime: [],
        });
    }

    onChangeRadio = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows,
            showConfirmButton: selectedRowKeys.length > 0
        });
    }

    onCloseTag = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'saleOrderPanel.validate.saleOrder',
                defaultMessage: '请选择KD销售订单'
            }));
        this.props.onSelect(this.state.selectedRows[0]);
    }
    
    onDelete=id => {
        const keys = this.state.selectedRowKeys.filter(k => k !== id);
        const rows = this.state.selectedRows.filter(r => r.id !== id);
        this.setState({
            selectedRowKeys: [...keys],
            selectedRows: [...rows]
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'saleOrderPanel.column.code',
                    defaultMessage: '订单编号'
                }),
                sorter: true,
                dataIndex: 'code'
            }, {
                title: formatMessage({
                    id: 'saleOrderPanel.column.brand',
                    defaultMessage: '品牌'
                }),
                sorter: true,
                dataIndex: 'brandId',
                render: (text, record) => `(${record.brandCode})${record.brandName}`
            }, {
                title: formatMessage({
                    id: 'saleOrderPanel.column.dealer',
                    defaultMessage: '总代'
                }),
                sorter: true,
                dataIndex: 'dealreId',
                render: (text, record) => `(${record.dealerCode})${record.dealerName}`
            }, {
                title: formatMessage({
                    id: 'saleOrderPanel.column.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country',
            }, {
                title: formatMessage({
                    id: 'saleOrderPanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            }, {
                title: formatMessage({
                    id: 'saleOrderPanel.column.tradeMethodName',
                    defaultMessage: '贸易方式'
                }),
                dataIndex: 'tradeMethodName',
            }, {
                title: formatMessage({
                    id: 'saleOrderPanel.column.paymentType',
                    defaultMessage: '付款方式'
                }),
                dataIndex: 'paymentType',
                render: text => conventEnumValueToString(paymentType, text)
            }, {
                title: formatMessage({
                    id: 'saleOrderPanel.column.transportType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'transportType',
                render: text => conventEnumValueToString(saleOrderTransportType, text)
            }, {
                title: formatMessage({
                    id: 'saleOrderPanel.column.salesOrderPriceTerms',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'salesOrderPriceTerms',
                render: text => conventEnumValueToString(saleOrderPriceTerms, text)
            }
        ];
            

        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            type: 'radio',
            fixed: true,
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys,
                    selectedRows
                });
            },
            getCheckboxProps: record => ({
                disabled: (this.props.saleOrderId === record.id)
            })
        };
        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record);
            }
        });
        const selectRows = this.state.selectedRows.length ? [{
            text: this.state.selectedRows[0].code,
            value: this.state.selectedRows[0].id
        }] : [];
        return (
            <Modal
                title={formatMessage({
                    id: 'saleOrderPanel.show.query',
                    defaultMessage: '整车KD销售订单查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'saleOrderPanel.form.code',
                                defaultMessage: '订单编号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="code"
                                value={this.state.code}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'saleOrderPanel.form.orderType',
                                defaultMessage: '订单类型'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="orderType"
                                value={data.orderType}
                                options={saleOrderType.toList(language)}
                                onChange={this.onChange}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'saleOrderPanel.form.carrierCode',
                                defaultMessage: '货代编号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="carrierCode"
                                value={this.state.carrierCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'saleOrderPanel.form.batchNumber',
                                defaultMessage: '批次号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="batchNumber"
                                value={this.state.batchNumber}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'saleOrderPanel.form.createTime',
                                defaultMessage: '创建时间'
                            })}
                            {...FORM_OPTIONS.item}>
                            <DateRangePicker
                                name="createTime"
                                value={this.state.createTime}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'saleOrderPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'saleOrderPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <SelectAlert data={selectRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    onRow={onRow}
                    {...TABLE}/>
            </Modal >
        );
    }
}

SaleOrderPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    brandId: PropTypes.string,
    dealerId: PropTypes.string,
    intl: PropTypes.object,
    partOrderTypeId: PropTypes.string,
    transportType: PropTypes.number,
    onCancel: PropTypes.func,
};

export default injectIntl(SaleOrderPanel);
